package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Slf4j
@Service
public class TaskServiceImpl implements TaskService {
    @Autowired
    private TaskinfoMapper taskinfoMapper;
    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;
    @Autowired
    private CacheService cacheService;

    /**
     * 添加任务
     * @param task 任务
     * @return 任务id
     */
    @Override
    public long addTask(Task task) {
        // 1. 添加任务到数据库
        boolean flag = addTaskToDb(task);
        // 2. 如果数据库添加成功，将任务添加到redis中
        if (flag){
            addTaskToCache(task);
            // 3. 返回任务id
            return task.getTaskId();
        }
        throw new RuntimeException("添加任务失败");
    }

    /**
     * 取消任务
     *
     * @param taskId
     */
    @Override
    public boolean cancelTask(Long taskId) {
        boolean flag = false;
        // 1. 删除taskinfo表中的任务，更新taskinfo_logs表的状态
        Task task = updateDb(taskId,ScheduleConstants.CANCELLED);
        // 2. 如果返回的task不为空，删除redis中的任务数据
        if (task != null){
            removeTaskFromCache(task);
            flag = true;
        }
        // 2. 返回成功标记
        return flag;
    }

    /**
     * 消费任务
     *
     * @param taskType 任务类型
     * @param priority 任务优先级
     * @return 任务对象
     */
    @Override
    public Task poll(Integer taskType, Integer priority) {
        Task task = null;
        try {
            String key = ScheduleConstants.TOPIC + taskType +"_"+priority;
            // 从list中按照类型和优先级移除并返回最右侧元素
            String jsonStr = cacheService.lRightPop(key);
            if (StringUtils.isNotBlank(jsonStr)){
                task = JSON.parseObject(jsonStr, Task.class);
                // 3. 删除taskinfo表中的数据，修改taskinfo_logs表的状态
                updateDb(task.getTaskId(),ScheduleConstants.EXECUTED);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return task;
    }

    private void removeTaskFromCache(Task task) {
        String key = task.getTaskType()+"_"+task.getPriority();
        // 删除list
        cacheService.lRemove(ScheduleConstants.TOPIC+key,0,JSON.toJSONString(task));
        // 删除zset
        cacheService.zRemove(ScheduleConstants.FUTURE+key,JSON.toJSONString(task));
    }

    /**
     * 删除taskinfo表中的任务
     * 更新taskinfo_logs表的状态
     * 返回任务对象
     * @return
     */
    private Task updateDb(Long taskId, int status) {
        Task task = null;
        try {
            // 1. 删除taskinfo表中的任务
            taskinfoMapper.deleteById(taskId);
            // 2. 更新taskinfo_logs表的状态
            TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);
            taskinfoLogs.setStatus(status);
            taskinfoLogsMapper.updateById(taskinfoLogs);

            task = new Task();
            BeanUtils.copyProperties(taskinfoLogs, task);
            task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());
        } catch (BeansException e) {
            e.printStackTrace();
        }
        // 3.返回任务对象
        return task;
    }

    /**
     * 添加任务到redis
     * @param task
     */
    private void addTaskToCache(Task task) {
        // 构造key
        String key = task.getTaskType()+"_"+ task.getPriority();
        // 未来时间(当前时间+5分钟)
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);
        long futureTime = calendar.getTimeInMillis();
        if (task.getExecuteTime() <= System.currentTimeMillis()){
            // 如果任务的执行时间<=当前系统时间，直接存入list
            cacheService.lLeftPush(ScheduleConstants.TOPIC+key, JSON.toJSONString(task));
        }else if (task.getExecuteTime() <= futureTime){
            // 如果任务的执行时间 > 当前系统时间 && <= 预设时间，存入zset
            cacheService.zAdd(ScheduleConstants.FUTURE+key,JSON.toJSONString(task), task.getExecuteTime());
        }
    }

    /**
     * 添加任务到数据库
     * @param task
     * @return
     */
    private boolean addTaskToDb(Task task) {
        boolean flag = true;
        try {
            // 1. 将任务添加到taskinfo表
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(task, taskinfo);
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
            taskinfoMapper.insert(taskinfo);
            // 2. 将taskId，设置到task对象中
            task.setTaskId(taskinfo.getTaskId());
            // 3. 将任务日志添加到taskinfo_logs表
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtils.copyProperties(taskinfo, taskinfoLogs);
            taskinfoLogs.setVersion(1);
            taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);
            taskinfoLogsMapper.insert(taskinfoLogs);
        } catch (BeansException e) {
            e.printStackTrace();
            log.error("添加任务到数据库失败{}",task);
            flag = false;
        }
        return flag;
    }

    /**
     * 每隔一分钟将zset中的任务(任务的执行时间<=当前时间)同步到list中
     */
    @PostConstruct  // spring bean的声明周期方法注册  bean的初始化方法
    @Scheduled(cron = "0 */1 * * * ?")
    public void refresh(){
        // 尝试获取锁
        String token = cacheService.tryLock("FUTURE_TASK_SYNC", 3000 * 10);
        if (StringUtils.isNotBlank(token)){
            // 获取到了锁，开始进行数据同步
            log.info("未来任务定时刷新到list");
            // 1. 从redis中获取所有未来任务的key
            Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
            if (CollectionUtils.isEmpty(futureKeys)){
                return;
            }
            // 2. 遍历key的集合
            for (String futureKey : futureKeys) { // future_100_50  --->  topic_100_50
                String topicKey = futureKey.replace(ScheduleConstants.FUTURE,ScheduleConstants.TOPIC);
                // 3. 获取当前key中分数范围是从0到当前系统时间的元素
                Set<String> jsonTasks = cacheService.zRangeByScore(futureKey, 0, System.currentTimeMillis());
                // 3. 将数据同步到list集合中
                cacheService.refreshWithPipeline(futureKey,topicKey,jsonTasks);
            }
        }
    }


    @PostConstruct
    @Scheduled(cron = "0 */5 * * * ?")
    public void reloadData(){
        // 1. 清除redis中的已有任务，避免任务重复添加
        clearCache();
        // 2. 从数据库中查询执行时间<=未来5分钟的任务
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);
        LambdaQueryWrapper<Taskinfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.lt(Taskinfo::getExecuteTime,calendar.getTime());
        List<Taskinfo> taskinfos = taskinfoMapper.selectList(wrapper);
        // 3. 将任务添加到redis中
        for (Taskinfo taskinfo : taskinfos) {
            Task task = new Task();
            BeanUtils.copyProperties(taskinfo, task);
            task.setExecuteTime(taskinfo.getExecuteTime().getTime());
            addTaskToCache(task);
        }
    }

    /**
     * 清除redis中的已有任务
     */
    private void clearCache() {
        // 删除未来任务
        Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
        cacheService.delete(futureKeys);
        // 删除当前需要执行的任务
        Set<String> topicKeys = cacheService.scan(ScheduleConstants.TOPIC + "*");
        cacheService.delete(topicKeys);
    }
}
